package com.chentf.rabbitmq.workquene03;

import com.chentf.rabbitmq.utils.RabbitMqUtilsSGG;
import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

/*
 * 发布确认模式，
 * 2、批量确认
 * */
public class MoreTask3 {

    // 批量发消息的个数
    public static final int MESSAGE_COUNT = 1000;

    public static void main(String[] args) throws Exception {
        //2、批量确认
        // 发布1000个批量确认消息，耗时37ms
        MoreTask3.publishMessageBatch();
    }

    private static void publishMessageBatch() throws IOException, TimeoutException, InterruptedException {
        Channel channel = RabbitMqUtilsSGG.getChannel();
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,false,false,false,null);
        //开启发布确认
        channel.confirmSelect();
        //开始时间
        long start = System.currentTimeMillis();
        //批量确认消息大小
        int batchSize = 1000;
        //批量发送，批量确认
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = i + "";
            channel.basicPublish("",queueName,null,message.getBytes(StandardCharsets.UTF_8));
            //判断达到100条消息的时候，批量确认一次
            if(i % batchSize == 0){
                // 确认发布
                channel.waitForConfirms();
            }
        }
        //为了确保还有剩余没有确认消息 再次确认
        if (batchSize > 0) {
            channel.waitForConfirms();
        }
        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"条批量确认消息，耗时"+ (end - start) + "ms");
    }
}
